<?php

class Products_model extends CI_Model 
{	
	public $products = array();
	public $categorizedProducts = array();
	//private $categories = array();
	
    function __construct()
    {
        parent::__construct();
		
        //$this->initCategories();
        $this->initProducts();
    }
	
    private function initProducts() 
    {
    	$sql = "SELECT \n"
	    . "	products.id, \n"
	    . "	products.name, \n"
	    . "	products.description, \n"
	    . "	products.image_ids, \n"
	    . "	products.netto_price, \n"
	    . "	products.price, \n"
	    . "	products.profit_key, \n"
	    . "	products.category_id,\n"
	    . "	products.isFeatured,\n"
	    . "	categories.name as cat_name \n"
	    . "\n"
	    . "From products LEFT JOIN (categories)\n"
	    . "\n"
	    . "ON (products.category_id=categories.category_id)";
    	
    	$query = $this->db->query($sql);
    	
    	foreach ($query->result() as $row)
		{
            // __construct     ($id,      $name,      $description,      $images, $price,      $category_id,      $o_cat_name,    $isFeatured)
			$prod = new Product($row->id, $row->name, $row->description, null,    $row->price, $row->category_id, $row->cat_name, $row->isFeatured);
			/*
            $prod->id = $row->id;
			$prod->name = $row->name;
			$prod->description = $row->description;
			$prod->image_ids = $row->image_ids;
			$prod->netto_price = $row->netto_price;
			$prod->price = $row->price;
			$prod->profit_key = $row->profit_key;
			$prod->category_id = $row->category_id;
			$prod->isFeatured = $row->isFeatured;
			$prod->o_cat_name = $row->cat_name;
			*/

            /* TODO REF possible performace issue */
            $sql_get_images = "SELECT * FROM `images` WHERE id=1 LIMIT 0, 30 ";

			//array_push($this->products, $prod);
			/*if(!isset($this->categorizedProducts[$prod->category_id]))
			{
				$this->categorizedProducts[$prod->category_id] = array();
			}
			*/
			$this->products[$prod->id] = $prod;
			//$this->categorizedProducts[$prod->category_id][$prod->id] = $prod;
		}
    }
 
	public function isSubCat($subcatID, $parentID) {
		//echo '<p> ' .$subcatID. '  ,  '.$parentID;
		if(!array_key_exists($subcatID, $this->categories) || !array_key_exists($subcatID, $this->categories)) {
			return false;
		}
		
		do {
			if($subcatID == $parentID) return true;
			$subcatID = $this->getCategory($subcatID)->parent_id;
		} while(!is_null($subcatID));
		
		return false;
	}
	
	public function clearProductCategories($id)	{
		foreach ($this->products as $product)
		{
			if($this->startsWith($product->category_id, $id.""))
			{
				$product->category_id = 0;
				$product->update();
			}
		}
	}
	
	public function removeProduct($id) {
		$prod = $this->products[$id];
		$prod->delete();
		unset($this->products[$id]);
	}
    
	public function editProduct($id, $name, $description, $netto_price, $price, $profit_key, $category_id) 
	{
		$prod = $this->products[$id]; 
		$prod->id = $id;
		$prod->name = $name;
		$prod->description = $description;
		$prod->netto_price = $netto_price;
		$prod->price = $price;
		$prod->profit_key = $profit_key;
		$prod->category_id = $category_id;
		
		$prod->update();
	}
	
	public function firstCategoryProducts() {
		return $this->categorizedProducts(10);
	}
	
	public function allProducts() {
		$result = array();
		$i = 0;
		foreach($this->products as $prod) {
			$result[$i] = $prod;
			$i++;
		}
		
		return $result;
	}
	
	public function categorizedProducts($categoryID) {
		//echo "helloka! " . $categoryID;
		$result = array();
		$i = 0;
		foreach($this->products as $prod) {
			//echo " prod " . $prod->category_id . "   " . $categoryID;	
			if($this->startsWith($prod->category_id, $categoryID."")) {
				//echo "meccselés!!!!!";
				array_push($result, $prod->toJSON());
				//$result[$i] = $prod;
				//$i++;
			} else if($categoryID."" == "0" && $prod->category_id."" == "0" ) {
				array_push($result, $prod->toJSON());
			}
		}
		
		return $result;
	}
	
	private function startsWith($haystack, $needle)
	{
	    return $needle === "" || strpos($haystack, $needle) === 0;
	}
	
	public function breadCrumbs($categoryID) {
		$bread_crumbs = array();
		
		if ($categoryID >= 0 && $categoryID != null)
		{
			$cuerrentCategory = $this->categories[$categoryID];
			do {			
				$crumb = array(
				   'url'      => '/smaragd/products/category/' . $cuerrentCategory->id,
				   'name'  => $cuerrentCategory->name
				);
				
				array_push($bread_crumbs, $crumb);
				
				$cuerrentCategory = $cuerrentCategory->parent_category;
			} while ($cuerrentCategory != null); 
		}
		array_push($bread_crumbs, array('url' => '/smaragd/products/', 'name'  => 'Összes termék'));
		
		$response = '<ol class="breadcrumb" >';
		$index = 1;
		foreach(array_reverse($bread_crumbs) as $crumb)
		{
			$class = "";
			$link = '<a href="' . $crumb['url'] .'">' . $crumb['name'] . '</a>';
			if($index == sizeof($bread_crumbs)) {
				$class='"class="active"';
				$link=$crumb['name'];
			}
			
			$response = $response . '<li '.$class.'>'.$link.'</li>';
			$index++;
		}
		$response = $response . '</ol>';
		
		return $response;
	}
	
	
	
	public function getAllProducts() {
		return $this->products;
	}
	
	public function getOnlyCategorizedProducts() {
		$result = array();
		foreach($this->products as $prod) {
			if($prod->category_id != null) $result[$prod->id]=$prod;
		}
		return $result;
	}
	
	public function getFeaturedProducts() {
		$result = array();
		foreach($this->products as $prod) {
			if($prod->isFeatured == 1) $result[$prod->id]=$prod;
		}
		return $result;
	}
	
	public function getProductById($id) {
		foreach ($this->products as $product) {
			if($product->id == $id) return $product;
		}
		return null;
	}
	
	public function numberOfProductsIn($categoryID){
		$numOfProds = 0;
		foreach($this->products as $product) {
			if($this->isSubCat($product->category_id, $categoryID)) $numOfProds = $numOfProds+1;
		}
		return $numOfProds;
	}
	
	/*
	public function getCategory($id) {
		if(array_key_exists ( $id , $this->categories))
		{
			return $this->categories[$id];
		} else return new EmptyCategory;
	} */
}
?>